#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging.config
import datetime
import yaml
import os
from sanic import Sanic,response
from sanic.exceptions import RequestTimeout, NotFound
from . import load_config
from .db import database
from . import func
from .utils import *

# with open(os.path.join(os.path.dirname(__file__), 'logging.yml'), 'r') as f:
#     logging.config.dictConfig(yaml.load(f))
from .utils import set_auth_cookies,get_auth_cookies
config = load_config()
appid = config.get('APP_NAME', __name__)

app = Sanic(appid,error_handler=CustomHandler())
app.config = config
from multiprocessing import Pool,Process

@app.listener('before_server_start')
async def before_server_start(app, loop):

    # queue = asyncio.Queue()
    # app.queue = queue
    # reporter = AioReporter(queue=queue)
    # tracer = BasicTracer(recorder=reporter)
    # tracer.register_required_propagators()
    # opentracing.tracer = tracer
    # app.db = database
    app.set_auth_cookies = set_auth_cookies
    app.get_auth_cookies = get_auth_cookies

@app.listener('after_server_start')
async def notify_server_started(app, loop):
    app_dict = {'name': '', 'children': []}
    app_name = app.name
    app_dict['name'] = app_name
    for item in app.blueprints.values():
        group_data = {'name': '', 'children': []}
        group_name = item.name
        group_data.update({'name': group_name})
        group_children = []
        for rt in item.routes:
            path = ''.join([item.url_prefix, rt.uri])
            # print(path)
            name = rt.name
            methods = rt.methods
            group_children.append({
                    'path': path,
                    'name': name,
                    'methods': methods
            })
            group_data.update({'children': group_children})
        app_dict['children'].append(group_data)

    if app_name=='devtools':
        pass
    else:
        pp = Pool(1)
        url = app.config.get('APP_NOTIFY_URL', '')
        # for app_name in ['notify_app_service','app_name']:
        print('-------------------------------', url)
        pp.apply_async(func, args=(app_name, app, url, app_dict))
        pp.close()
        pp.join()

@app.middleware('request')
async def handle_request(request):
    pass
    # print(dir(database))
    # print(database.is_connection_usable())
    # request.app.db.autoconnect
    # request.app.db.connect()

@app.middleware('response')
async def handle_response(request, response):
    if not request.app.db.is_closed():
        request.app.db.close()

@app.middleware('response')
async def cors_res(request, response):
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Headers"] = "x-requested-with"
    response.headers["Access-Control-Allow-Methods"] = 'POST, GET, OPTIONS,DELETE'
    return response

@app.exception(RequestTimeout)
def timeout(request, exception):
    return response.json({'message': 'Request Timeout'}, 408)


@app.exception(NotFound)
def notfound(request, exception):
    return response.json(
        {'message': 'Requested URL {} not found'.format(request.url)}, 404)
